package com.talent.web.config.security;

import com.google.gson.Gson;
import com.talent.web.enums.ResponseEnum;
import com.talent.web.model.TalentResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName：TalentAuthenticationFailureHandler
 * @Author: hszhou
 * @Date: 2025/2/27 9:10
 * @Description: 登陆失败时走的处理器
 */

@Service
public class TalentAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private static final Logger logger = LoggerFactory.getLogger(TalentAuthenticationFailureHandler.class);

    @Autowired
    private Gson gson;
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        //用户名或密码错误
        logger.error("登录失败【{}】",exception.getMessage());
        TalentResult<Object> result =TalentResult.error(ResponseEnum.USERNAME_OR_PASSWORD_ERROR);

        String json = gson.toJson(result);
        writer.println(json);
    }
}
